<template>
  <div style="height: 100%">
    <el-scrollbar style="height: 100%">
      <el-row v-show="showSearch" class="query_el_row-wrapper" style="margin: 0;padding-bottom: 18px;">
        <el-col :span="17">
          <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="queryDataList">
            <el-form-item label="消息类型" prop="messageType">
              <el-select v-model="state.queryForm.messageType" placeholder="请选择消息类型">
                <el-option label="请选择" value="">全部</el-option>
                <el-option label="BINGCHONG_ALARM" value="BINGCHONG_ALARM"></el-option>
                <el-option label="BEST_ALARM" value="BEST_ALARM"></el-option>
                <!-- 若有其他消息类型，可在此继续添加 -->
              </el-select>
            </el-form-item>
            <el-form-item label="上传时间" prop="createTime">
              <el-date-picker type="datetime" placeholder="请输入上传时间" v-model="state.queryForm.createTime"></el-date-picker>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="7">
          <div class="query_button_wrap">
            <el-button icon="search" type="primary" @click="queryDataList">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>

        </el-col>
      </el-row>


      <el-row class="add_el_row_wrapper" style="background: white;margin: 0;padding-bottom: 18px;padding-left: 20px">
        <el-col :span="15" class="add_el_button_el_col">
          <el-button plain :disabled="multiple" icon="Delete" type="primary"
                     @click="handleDelete(selectObjs)">
            删除
          </el-button>
        </el-col>
        <el-col :span="9" class="right_tool_el_col">
          <div style="margin-right: 10px"></div>
          <right-toolbar v-model:showSearch="showSearch" :export="'duorou_duorouKgbotcamFile_export'"
                         @exportExcel="exportExcel" class="ml10 mr20" style="float: right;"
                         @queryTable="queryDataList"></right-toolbar>
        </el-col>

      </el-row>

      <el-row v-show="showSearch" v-if="false">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="queryDataList">
          <el-form-item label="图片检测状态" prop="predictStatus">
            <el-select v-model="state.queryForm.predictStatus" placeholder="请选择图片检测状态：待检测、健康、不健康">
              <el-option label="请选择">全部</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传时间" prop="createTime">
            <el-date-picker type="datetime" placeholder="请输入上传时间" v-model="state.queryForm.createTime"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="queryDataList">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row v-if="false">
        <div class="mb8" style="width: 100%">
          <el-button plain :disabled="multiple" icon="Delete" type="primary"
                     @click="handleDelete(selectObjs)">
            删除
          </el-button>
          <right-toolbar v-model:showSearch="showSearch" :export="'duorou_duorouKgbotcamFile_export'"
                         @exportExcel="exportExcel" class="ml10 mr20" style="float: right;"
                         @queryTable="queryDataList"></right-toolbar>
        </div>
      </el-row>

      <el-row class="data_list_show_el_row_wrapper">
        <div style="width: 100%;height: 1px"></div>
        <el-table :data="state.dataList" v-loading="state.loading"
                  :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                  @selection-change="selectionChangHandle"
                  @sort-change="sortChangeHandle">
          <el-table-column type="selection" width="40" align="center"/>
          <el-table-column type="index" label="#" width="60"/>
          <el-table-column prop="detectedFileName" label="预警图片"  width="130">
            <template #default="scope">
              <div style="width: 100%;cursor: pointer" @click="previewImg(scope,true)">
                <el-image :src="thisPageState.imgBaseUrl + getImageUrl(scope.row)" :fit="'cover'" style="width: 100px;height: 100px">

                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="messageType" label="消息类型" show-overflow-tooltip/>
          <el-table-column prop="messageDescribe" label="消息描述" show-overflow-tooltip/>
          <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip/>
          <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip/>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button icon="delete" text type="primary"
                         @click="handleDelete([scope.row.id])">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination"/>
    </el-scrollbar>
  </div>

  <!--  预览原始抓取图片-->
  <el-image-viewer v-if="thisPageState.showCapImg" :url-list="thisPageState.camCapimgList"
                   :initial-index="thisPageState.capImgViewIndex" @close="thisPageState.showCapImg=false">
  </el-image-viewer>

  <!--  预览检测后的图片-->
  <el-image-viewer v-if="thisPageState.showCapImgDetected" :url-list="thisPageState.camCapDetectedList"
                   :initial-index="thisPageState.capImgDetectedViewIndex" @close="thisPageState.showCapImgDetected=false">

  </el-image-viewer>
</template>

<script setup lang="ts" name="systemDuorouKgbotcamFileDataCap">
import { ref, reactive, getCurrentInstance } from 'vue';
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/iot/iotDeviceMessage";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';

const { proxy } = getCurrentInstance();

/**
 * 定义组件属性 接收传递来的 大棚ID
 */
const props = defineProps({
  iotDevice: {
    type: Object,
    default: () => {},
  },
});

// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    devId: props.iotDevice.id,
    messageType: '',
    createTime: null
  },
  pageList: fetchList,
  handleDataListcallBack: getPreviewImagListByDataTable
});

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state);

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields();
  // 清空多选
  selectObjs.value = [];
  queryDataList();
};

// 导出excel
const exportExcel = () => {
  downBlobFile('/duorou/duorouKgbotcamFile/export', Object.assign(state.queryForm, { ids: selectObjs }), 'duorouKgbotcamFile.xlsx');
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    queryDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};


function queryDataList() {
  state.queryForm.createTime = proxy.parseTime(state.queryForm.createTime);
  getDataList(getPreviewImagListByDataTable);
}

/**
 * 自己定义的页面state
 */
const thisPageState = reactive({
  camCapimgList: [],
  showCapImg: false,
  capImgViewIndex: 0,

  camCapDetectedList: [],
  showCapImgDetected: false,
  capImgDetectedViewIndex: 0,

  imgBaseUrl: "/api"
});

/**
 * 获取后端地址
 */
thisPageState.imgBaseUrl = import.meta.env.VITE_API_URL;

/**
 * 从 messageSpecialInfo 中提取图片 URL
 */
function getImageUrl(item) {
  const match = item.messageSpecialInfo.match(/url=([^}]+)/);
  return match ? match[1] : '';
}

/**
 * 获取数据图片的预览列表
 */
function getPreviewImagListByDataTable() {
  // 对数据按 createTime 进行倒序排序
  state.dataList = state.dataList?.sort((a, b) => {
    const timeA = new Date(a.createTime).getTime();
    const timeB = new Date(b.createTime).getTime();
    return timeB - timeA;
  });

  let list = [];
  list = state.dataList?.map(v => thisPageState.imgBaseUrl + getImageUrl(v)) ?? [];
  thisPageState.camCapimgList = list;
  thisPageState.camCapDetectedList = list;
}

/**
 * 预览图片
 * @param scope
 * @param isDetected
 */
function previewImg(scope, isDetected) {
  console.log(scope);
  if (isDetected) {
    thisPageState.showCapImgDetected = true;
    thisPageState.capImgDetectedViewIndex = scope.$index;
  } else {
    thisPageState.showCapImg = true;
    thisPageState.capImgViewIndex = scope.$index;
  }
}
</script>

<style scoped lang="scss">

</style>